#include <apue.h>
static jmp_buf env_alrm;

static void sig_alrm(int signo)
{
	int i, j;
	volatile int k = 0;
	for(i = 0; i < 30; i++)
		for(j = 0; j < 40000; j++)
		{
			k += i * j;
			printf("from alrm\n");
		}
}

unsigned int sleep2(unsigned int nsecs)
{
//	if(signal(SIGALRM, sig_alrm) == SIG_ERR)
//		return (nsecs);
	struct sigaction act, oact;
	act.sa_handler = sig_alrm;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	sigaddset(&act.sa_mask, SIGINT);
	sigaddset(&act.sa_mask, SIGQUIT);
	if(sigaction(SIGALRM, &act, &oact) < 0)
		return (nsecs);
	if(setjmp(env_alrm) == 0)
	{
		alarm(nsecs);
		pause();
	}
	return (alarm(0));
}

static void sig_int(int signo)
{
	static int count = 0;
	int i, j;
	volatile int k;
	printf("\nsig_int starting\n");
	printf("%u\n", getpid());
	printf("p: %ld\n", pthread_self());
	for(i = 0; i < 30; i++)
		for(j = 0; j < 40000; j++)
		{
			k += i * j;
			printf("from int count=%d\n", count);
		}
	printf("sig_int finished\n");
	count++;
}

int main(int argc, char* argv[])
{
	unsigned int unslept;
	printf("%u\n", getpid());
	printf("p: %ld\n", pthread_self());
//	if(signal(SIGINT, sig_int) == SIG_ERR)
//		printf("signal(SIGINT) ERROR\n");
	struct sigaction act, oact;
	act.sa_handler = sig_int;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	sigaddset(&act.sa_mask, SIGALRM);
	sigaddset(&act.sa_mask, SIGQUIT);
	if(sigaction(SIGINT, &act, &oact) < 0)
	{
		printf("signal(SIGINT ERROR\n");
		exit(0);
	}
	unslept = sleep2(5);
	printf("sleep2 returned : %u\n", unslept);
	return 0;
}
